# 互斥锁 牺牲效率，将并发变为串行，保证数据安全
# 一般不使用锁，容易造成死锁
# 一般只在争抢数据时使用
from multiprocessing import Process, Lock
import time
import json
import random


def search(i):
    # 文件操作读取票数
    with open('data', 'r', encoding='utf-8') as f:
        dic = json.load(f)
    print(f"用户{i}查询余票:{dic.get('ticket_num')}")


def buy(i):
    with open('data', 'r', encoding='utf-8') as f:
        dic = json.load(f)
    time.sleep(random.randint(1, 2))
    if dic.get('ticket_num') > 0:
        dic['ticket_num'] -= 1
        with open('data', 'w', encoding='utf-8') as f:
            json.dump(dic, f)
        print(f"用户{i}购票成功")
    else:
        print(f"用户{i}购票失败")


def run(i, mutex):
    search(i)
    # 给买票环节加锁
    # 抢锁
    mutex.acquire()
    buy(i)
    # 释放锁
    mutex.release()


if __name__ == '__main__':
    #  主进程生成锁
    mutex = Lock()
    for i in range(1, 11):
        p = Process(target=run, args=(i, mutex))
        p.start()
